package com.cb.controller;

import com.cb.common.BaseContext;
import com.cb.common.R;
import com.cb.entity.AddressBook;
import com.cb.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新增地址
     */
    @PostMapping
    public R<AddressBook> save(@RequestBody AddressBook addressBook){
        addressBook.setUserId(BaseContext.getCurrentId());
        log.info("addressBook:{}", addressBook);

        addressBookService.save(addressBook);
        return R.success(addressBook);
    }

    /**
     * 修改地址
     */
    @PutMapping
    public R<String> updateAddress(@RequestBody AddressBook addressBook){
        addressBookService.updateAddress(addressBook);
        return R.success("修改成功！");
    }

    /**
     * 删除地址
     */
    @DeleteMapping
    public R<String> deleteAddress(@RequestParam String ids){
        addressBookService.removeById(ids);
        return R.success("删除成功！");
    }

    /**
     * 设置默认地址
     */
    @PutMapping("/default")
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook){
        Long currentId = BaseContext.getCurrentId();
        addressBook.setUserId(currentId);
        AddressBook addressBook1=addressBookService.setDefault(addressBook);
        return R.success(addressBook1);
    }

    /**
     * 根据id查询地址
     */
    @GetMapping("/{id}")
    public R get(@PathVariable Long id){
        AddressBook addressBook = addressBookService.getById(id);
        if(addressBook!=null){
            return R.success(addressBook);
        }else {
            return R.error("没有找到该对象！");
        }
    }

    /**
     * 查询指定用户的全部地址
     */
    @GetMapping("/list")
    public R<List<AddressBook>> list(){
        Long currentId = BaseContext.getCurrentId();
        List<AddressBook> addressBooks=addressBookService.getList(currentId);
        return R.success(addressBooks);
    }

    /**
     * 查询默认地址
     */
    @GetMapping("/default")
    public R<AddressBook> getDefault(){
        AddressBook addressBook=addressBookService.getDefault();
        if (addressBook==null) {
            return R.error("没有找到该对象!");
        }else {
            return R.success(addressBook);
        }
    }


}
